<template>
  <div class="app-container">
    <el-form ref="noticedemandapprovalRef" :model="formData" :rules="rules" label-width="140px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="立案号" prop="caseId">
            <el-select
              v-model="formData.caseId"
              placeholder="请选择立案号"
              :disabled="disabled"
              clearable
              @change="handleCase">
              <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="催告书文号" prop="demandNo">
            <el-input v-model="formData.demandNo" disabled placeholder="请输入催告书文号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请人名称" prop="applicantName">
            <el-input v-model="formData.applicantName" disabled placeholder="请输入申请人名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="地址" :rules="rules.applicantAddress" prop="applicantAddress">
            <el-input v-model="formData.applicantAddress" disabled placeholder="请输入地址" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="法定代表人" prop="applicantLegalReptive">
            <el-input v-model="formData.applicantLegalReptive" :disabled="disabled" placeholder="请输入法定代表人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="职务" prop="applicantPosition">
            <el-input v-model="formData.applicantPosition" :disabled="disabled" placeholder="请输入职务" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="电话" prop="applicantPhone">
            <el-input v-model="formData.applicantPhone" :disabled="disabled" placeholder="请输入电话" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="邮政编码" prop="applicantPostalCode">
            <el-input v-model="formData.applicantPostalCode" :disabled="disabled" placeholder="请输入邮政编码" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="委托代理人姓名" prop="agentName">
            <el-input v-model="formData.agentName" :disabled="disabled" placeholder="请输入委托代理人姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工作单位" prop="agentWorkUnit">
            <el-input v-model="formData.agentWorkUnit" :disabled="disabled" placeholder="请输入工作单位" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="电话" prop="agentPhone">
            <el-input v-model="formData.agentPhone" :disabled="disabled" placeholder="请输入电话" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="职务" prop="agentPosition">
            <el-input v-model="formData.agentPosition" :disabled="disabled" placeholder="请输入职务" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="被申请人名称或姓名" prop="partyName" class="long-label">
            <el-input v-model="formData.partyName" disabled placeholder="请输入被申请人名称或姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="法定代表人(负责人)姓名" prop="legalRepresentative" class="long-label">
            <el-input v-model="formData.legalRepresentative" disabled placeholder="请输入法定代表人姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="电话" prop="contactPhone">
            <el-input v-model="formData.contactPhone" disabled placeholder="请输入电话" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="邮政编码" prop="postalCode">
            <el-input v-model="formData.postalCode" disabled placeholder="请输入邮政编码" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="地址" :rules="rules.addressObj" prop="addressObj">
            <locationSelect v-model="formData.addressObj" disabled style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="案由" :rules="rules.caseCause" prop="caseCause">
            <!-- 案由 -->
            <el-input
              v-model="formData.caseCause"
              type="textarea"
              :rows="4"
              readonly
              placeholder="请选择案由"
              style="cursor: pointer"
              @click="
                () => {
                  getCaseContent('', '1', 'caseCause')
                  showCausePicker = true
                }
              " />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="行政处罚决定书文号" prop="decisionsNo" class="long-label">
            <el-input v-model="formData.decisionsNo" placeholder="请输入行政处罚决定书文号" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="催告理由" prop="noticeDemandReason">
            <SmartTextInput
              v-model="formData.noticeDemandReason"
              type="textarea"
              :disabled="disabled"
              :rows="4"
              placeholder="请输入催告理由"
              :min-length="2"
              :max-suggestions="5"
              contentType="100" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="履行的义务" prop="noticeFollowContent">
            <SmartTextInput
              v-model="formData.noticeFollowContent"
              type="textarea"
              :disabled="disabled"
              :rows="4"
              placeholder="请输入履行的义务"
              :min-length="2"
              :max-suggestions="5"
              contentType="100" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 案由选择弹窗 -->
    <el-dialog v-model="showCausePicker" title="选择案由" width="500px" :before-close="closeCausePicker">
      <el-select
        v-model="formData.caseCauseId"
        clearable
        filterable
        placeholder="请选择案由"
        style="width: 100%"
        @change="selectCaseCause">
        <el-option v-for="(item, index) in caseCauseList" :key="item.id" :label="item.content" :value="item.id" />
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeCausePicker">取消</el-button>
          <el-button type="primary" @click="confirmCaseCause">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, watch } from 'vue'
import {
  getCompulsoryItemApprovalResult,
  addCompulsoryItemApprovalResult,
  updateCompulsoryItemApprovalResult,
  getCaseList,
  getContent,
  previewPdf,
} from '@/api/enforcement/index.js'
import { registrationcaseDetail } from '@/api/filingReview/register'
import { ElMessage } from 'element-plus'
import locationSelect from '@/components/locationSelect/index.vue'
import CaseSituation from '@/components/CaseSituation/index.vue'
import SmartTextInput from '@/components/SmartTextInput/index.vue'
import { commonRules } from '@/components/DynamicForm/config'
import { commontermsGet } from '@/api/filingReview/register.js'

const { proxy } = getCurrentInstance()

// Props
const props = defineProps({
  id: {
    type: [String, Number],
    default: null,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
})

// Emits
const emit = defineEmits(['handleSubmit'])

// Form data
const formData = ref({
  id: null,
  caseId: null,
  caseNo: null,
  decisionsNo: null,
  demandYear: null,
  demandSerialNo: null,
  demandNo: null,
  partyName: null,
  streetOfCompanyAddress: null,
  address: null,
  unifiedSocialCreditCode: null,
  legalRepresentative: null,
  productionDate: null,
  noticeDate: null,
  teamLeaderOpinion: null,
  legalHandlerOpinion: null,
  legalLeaderHandlerOpinion: null,
  handlerLeaderOpinion: null,
  applyTime: null,
  status: null,
  createBy: null,
  productionDate: null,
  updateBy: null,
  updateTime: null,
  delFlag: null,
  caseCause: null,
  caseCauseId: null,
  decisionsNo: null,
  noticeDemandReason: null,
  noticeFollowContent: null,
})
// 自定义校验器：检查拍摄地点是否完整
const validateLocation = (rule, value, callback) => {
  if (!value || !value.streetOfPhotoLocation || !value.photoLocation) {
    callback(new Error('请选择地点'))
  } else {
    callback()
  }
}
// Form validation rules
const rules = {
  caseId: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  demandNo: [{ required: true, message: '催告书文号不能为空', trigger: ['blur', 'change'] }],
  applicantName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
  applicantAddress: [{ required: true, message: '当事人地址不能为空', trigger: ['blur', 'change'] }],
  applicantLegalReptive: [{ required: true, message: '法定代表人不能为空', trigger: ['blur', 'change'] }],
  applicantPosition: [{ required: true, message: '职务不能为空', trigger: ['blur', 'change'] }],
  applicantPhone: [commonRules.phone],
  applicantPostalCode: [commonRules.postCode],
  agentName: [{ required: true, message: '受委托人姓名不能为空', trigger: ['blur', 'change'] }],
  agentWorkUnit: [{ required: true, message: '工作单位不能为空', trigger: ['blur', 'change'] }],
  agentPhone: [commonRules.phone],
  agentPosition: [{ required: true, message: '职务不能为空', trigger: ['blur', 'change'] }],
  partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
  legalRepresentative: [{ required: true, message: '法定代表人不能为空', trigger: ['blur', 'change'] }],
  contactPhone: [commonRules.phone],
  postalCode: [commonRules.postCode],
  addressObj: [{ required: true, validator: validateLocation, trigger: ['blur', 'change'] }],
  caseCause: [{ required: true, message: '案由不能为空', trigger: ['blur', 'change'] }],
  decisionsNo: [{ required: true, message: '行政处罚决定书文号不能为空', trigger: ['blur', 'change'] }],
  noticeDemandReason: [{ required: true, message: '催告理由不能为空', trigger: ['blur', 'change'] }],
  noticeFollowContent: [{ required: true, message: '履行的义务不能为空', trigger: ['blur', 'change'] }],
}

// Refs
const noticedemandapprovalRef = ref()

// Methods
const reset = () => {
  formData.value = {
    id: null,
    caseId: null,
    caseNo: null,
    decisionsNo: null,
    demandYear: null,
    demandSerialNo: null,
    demandNo: null,
    partyName: null,
    streetOfCompanyAddress: null,
    address: null,
    unifiedSocialCreditCode: null,
    legalRepresentative: null,
    productionDate: null,
    noticeDate: null,
    teamLeaderOpinion: null,
    legalHandlerOpinion: null,
    legalLeaderHandlerOpinion: null,
    handlerLeaderOpinion: null,
    applyTime: null,
    status: null,
    createBy: null,
    productionDate: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
  }
  proxy.resetForm('noticedemandapprovalRef')
}

// Get detail data
const getDetail = async id => {
  reset()
  if (id) {
    try {
      const res = await getCompulsoryItemApprovalResult(id)
      formData.value = res.data
      formData.value.addressObj = {
        photoLocation: res.data.address,
        streetOfPhotoLocation: res.data.streetOfCompanyAddress,
      }
    } catch (error) {
      console.error('获取详情失败:', error)
    }
  }
}

const handleCase = async val => {
  return new Promise(async (resolve, reject) => {
    if (!val) {
      formData.value.caseNo = ''
      formData.value.decisionsNo = ''
      formData.value.partyName = ''
      formData.value.partyId = ''
      formData.value.legalRepresentative = ''
      formData.value.businessType = ''
      formData.value.creditCode = ''
      formData.value.addressObj = {
        photoLocation: '',
        streetOfPhotoLocation: '',
      }
      formData.value.applicantAddress = ''
      formData.value.contactPhone = ''
      formData.value.postalCode = ''
      return
    }
    const res = await registrationcaseDetail(val)
    const {
      caseCauseId,
      partyName,
      partyId,
      legalRepresentative,
      businessType,
      unifiedSocialCreditCode,
      streetOfCompanyAddress,
      address,
      contactPhone,
      postalCode,
    } = res.data
    formData.value.caseNo = res.data.caseNo
    formData.value.partyName = partyName
    formData.value.partyId = partyId
    formData.value.legalRepresentative = legalRepresentative
    formData.value.businessType = businessType
    formData.value.creditCode = unifiedSocialCreditCode
    formData.value.caseCause = res.data.caseCause
    formData.value.caseCauseId = caseCauseId
    formData.value.caseCauseId = res.data.caseCauseId
    formData.value.contactPhone = contactPhone
    formData.value.postalCode = postalCode
    formData.value.addressObj = {
      photoLocation: address,
      streetOfPhotoLocation: streetOfCompanyAddress,
    }
    const res2 = await getContent(val)
    formData.value.decisionsNo = res2.data.decisionsNo
    formData.value.applicantAddress = res2.data.applicantAddress
    formData.value.demandNo = res2.data.demandNo
    formData.value.applicantName = res2.data.applicantName
    formData.value.noticeDemandReason = res2.data.noticeDemandReason
    formData.value.noticeFollowContent = res2.data.noticeFollowContent
    formData.value.demandId = res2.data.demandId
    formData.value.compulsoryItemApprovalId = res2.data.compulsoryItemApprovalId
    resolve()
  })
}

// 案由 相关 start ==========================================================
const showCausePicker = ref(false)
const caseCauseList = ref([])

const selectCaseCause = val => {
  formData.value.caseCauseId = val
}

const closeCausePicker = () => {
  showCausePicker.value = false
  formData.value.caseCauseId = formData.value.caseCauseId || ''
}

const confirmCaseCause = () => {
  // 案由选中
  if (formData.value.caseCauseId === undefined) {
    formData.value.caseCauseId = ''
    formData.value.caseCause = ''
    return
  }
  formData.value.caseCause = caseCauseList.value.find(i => i.id === formData.value.caseCauseId)?.content || ''
  showCausePicker.value = false
}

async function getCaseContent(parentType, type, field) {
  const res = await commontermsGet({
    termType: type,
    pageSize: 9999,
    pageNum: 1,
    status: 0,
    parentId: parentType,
  })
  caseCauseList.value = res.data
  formData.value[field] = res.data[0].content
}

// 案由 相关 end ==========================================================

const handlePreview = () => {
  return new Promise(resolve => {
    submitForm(true)
      .then(async params => {
        previewPdf(params)
          .then(res => {
            if (!!res.msg) {
              window.open(res.msg)
              resolve()
            } else {
              ElMessage.warning('预览文件不存在')
              resolve()
            }
          })
          .catch(() => {
            ElMessage.warning('预览文件不存在')
            resolve()
          })
      })
      .catch(() => {
        ElMessage.warning('请先完善表单信息')
        resolve()
      })
  })
}

// Submit form
const caseSituationRef = ref(null)
const submitForm = (isPreview = false) => {
  return new Promise(async (resolve, reject) => {
    noticedemandapprovalRef.value
      .validate()
      .then(async () => {
        formData.value.address = formData.value.addressObj.photoLocation
        formData.value.streetOfCompanyAddress = formData.value.addressObj.streetOfPhotoLocation
        if (isPreview === true) {
          resolve(formData.value)
          return
        }
        let result
        if (formData.value.id) {
          result = await updateCompulsoryItemApprovalResult(formData.value)
        } else {
          result = await addCompulsoryItemApprovalResult(formData.value)
        }

        ElMessage.success('提交成功')
        emit('handleSubmit', result)
        return result
      })
      .catch(err => {
        reject(err)
      })
  })
}

// Watch props.id change
watch(
  () => props.id,
  newVal => {
    if (newVal) {
      getDetail(newVal)
    } else {
      reset()
    }
    handleCaseList()
  },
  { immediate: true }
)

const numberList = ref([])
async function handleCaseList() {
  const res = await getCaseList()
  numberList.value = res.data.map(item => ({
    label: item.caseNo,
    value: item.id,
  }))
}
// Expose methods
defineExpose({
  submitForm,
  handlePreview,
  reset,
  formData,
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
